package com.telecomdesign.playrepo;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;


/**
 * Upload Task
 */
public class UploadTask extends Task {
	
	private File module = null;
	
	private String modulename = null;
	
	private String repository = null;
	
	private String user = null;
	
	private String password = null;
	
	private String version = null;

	@Override
	public void execute() throws BuildException {
		try {
			if (null == module) {
				throw new BuildException("invalid module archive");
			}
			if (null == repository) {
				throw new BuildException("invalid repository url");
			}
			if (null == version) {
				version = "head";
			}
			if (null == modulename) {
				throw new BuildException("invalid name for module");
			}
			
			String url = repository;
			HttpClient client = new HttpClient();
	    	PostMethod pm = new PostMethod(url);
	    	Part[] parts = {
	    			new StringPart("version",version,"UTF-8"),
	    			new StringPart("module",modulename,"UTF-8"),
	    			new FilePart("archive", module)
	    	};
	    	
	    	pm.setRequestEntity(new MultipartRequestEntity(parts, pm.getParams()));
	    	int status = client.executeMethod(pm);
	    	
	    	if (HttpStatus.SC_OK != status) {
	    		throw new BuildException("Invalid Response status " + status);
	    	}
	    	
		} catch (FileNotFoundException e) {
			throw new BuildException(e);
		} catch (HttpException hte) {
			throw new BuildException(hte);
		} catch (IOException ioe) {
			throw new BuildException(ioe);
		}
	}

	public File getModule() {
		return module;
	}

	public void setModule(File module) {
		this.module = module;
	}

	public String getRepository() {
		return repository;
	}

	public void setRepository(String repository) {
		this.repository = repository;
	}

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getVersion() {
		return version;
	}

	public void setVersion(String version) {
		this.version = version;
	}

	public String getModulename() {
		return modulename;
	}

	public void setModulename(String modulename) {
		this.modulename = modulename;
	}	
	
	
}
